#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <limits.h>
#include "msgq.h"
#include "tools.h"

Ctos ctos;
Stoc stoc;


void login_acc(void)
{
	char path[PATH_MAX];
	sprintf(path,"%s/%u",ACC_PATH,ctos.acc.id);//获取账户文件路径
	int fd = open(path,O_RDWR|O_EXCL,0644);
	if(ERROR == fd)
	{
		perror("open acc");
		strcpy(stoc.str,"您输入的卡号不存在！\n");
	}
	else
	{
		Account aco;
		read(fd,&aco,sizeof(aco));
		printf("1.id=%d,pass=%d,name=%s,card=%s,money=%lf,errno=%d\n",aco.id,aco.pass,aco.name,aco.card,aco.money,aco.errno);
		if(2 < aco.errno)
		{	
			strcpy(stoc.str,"对不起，您输入的卡号已被锁定，请联系管理员解锁！\n");
		}		
		else if(ctos.acc.pass != aco.pass)
		{
			if(2 == aco.errno)
			{
				aco.errno = 3;
				lseek(fd,0,SEEK_SET);
				write(fd,&aco,sizeof(aco));			
				strcpy(stoc.str,"对不起，您输入的密码有误,已三次输入密码错误，帐号已锁定，请联系管理员解锁！\n");
			}
			else
			{
				aco.errno++;
				printf("err=%d\n",aco.errno);
				lseek(fd,0,SEEK_SET);
				write(fd,&aco,sizeof(aco));			
				strcpy(stoc.str,"对不起，您输入的密码有误,请重新登录！\n");
			}
		}
		else
		{
			aco.errno = 0;
			lseek(fd,0,SEEK_SET);
			write(fd,&aco,sizeof(aco));	
			sprintf(stoc.str,"%d",aco.pass);
		}
		printf("2.id=%d,pass=%d,name=%s,card=%s,money=%lf,errno=%d\n",aco.id,aco.pass,aco.name,aco.card,aco.money,aco.errno);
	}
	close(fd);
	// 返回信息
	stoc_send(&stoc);
}

int main()
{
	init_msgq();
	for(;;)
	{
		ctos_recv(&ctos,TYPE_LOGIN);
		stoc.type = ctos.pid;//反馈消息类型为进程号
		login_acc();
	}
}
